package com.yls.autoapply.config;

import com.yls.autoapply.model.SshConnection;
import com.yls.autoapply.util.ServerUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class ServerConfig implements EnvironmentAware, InitializingBean {

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void afterPropertiesSet() throws Exception {
        //读取application.yml，初始化DbProperties
        for (PropertySource<?> propertySource : ((StandardEnvironment) environment).getPropertySources()) {
            if (propertySource instanceof MapPropertySource) {
                if (propertySource.getName().startsWith("applicationConfig")) {
                    LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) propertySource.getSource();
                    List<String> allKey = map.keySet().stream().filter(k -> k.startsWith("autoapply.server.")).collect(Collectors.toList());
                    for (String key : allKey) {
                        Object value = map.get(key);
                        SshConnection conn = ServerUtil.put(key.split("\\.")[2]);
                        String properties = key.split("\\.")[3];
                        if ("ip".equalsIgnoreCase(properties)) {
                            conn.setIp((String) value);
                        } else if ("port".equalsIgnoreCase(properties)) {
                            conn.setPort(Integer.valueOf((Integer) value));
                        } else if ("user".equalsIgnoreCase(properties)) {
                            conn.setUser((String) value);
                        } else if ("pwd".equalsIgnoreCase(properties)) {
                            conn.setPwd((String) value);
                        } else if ("timeout".equalsIgnoreCase(properties)) {
                            conn.setTimeout((Integer) value);
                        }
                    }
                    for (String key : ServerUtil.getAllkey()) {
                        SshConnection sshConnection = ServerUtil.get(key);
                        System.out.println(sshConnection);
                    }
                }
            }
        }



        //System.out.println("配置的数据源" + allKey);

    }



}
